﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace AutoMapper
{

    public class EnumValueConverter<T>
        : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (targetType != typeof(string))
            {
                throw new NotSupportedException($"Failed to convert from {value?.GetType().FullName} to {targetType.FullName}. Only {typeof(string).FullName} is supported as target type.");
            }
            if (value == null)
            {
                return parameter;
            }
            var txt = ((T)value).GetCustomAttribute<T, EnumTextMetaAttribute>().Text;
            return txt;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (targetType != typeof(T))
            {
                throw new NotSupportedException($"Failed to convert from {value?.GetType().FullName} to {targetType.FullName}. Only {typeof(T).FullName} is supported as target type.");
            }
            var s = value as string;
            if (!string.IsNullOrWhiteSpace(s))
            {
                return s.ToEnumValue<T, EnumTextMetaAttribute>(x => x.Text);
            }
            else
            {
                if (parameter != null)
                {
                    return parameter;
                }
                else
                {
                    throw new ArgumentNullException($"{nameof(value)}", $"null value cannot be converted to type {typeof(T).FullName}.");
                }
            }
        }

    }

}
